document.addEventListener('DOMContentLoaded', () => {
    const items = JSON.parse(sessionStorage.getItem('selectedItems')) || [];
    const itemList = document.getElementById('itemList');
    const deliveryFee = 3;

    let total = 0;

    items.forEach(item => {
        const div = document.createElement('div');
        const subTotal = item.price * item.quantity;
        total += subTotal;

        div.innerHTML = `${item.name} × ${item.quantity} <span style="float:right">¥${item.price}</span>`;
        itemList.appendChild(div);
    });

    // 配送费
    const delivery = document.createElement('div');
    delivery.innerHTML = `配送费 <span style="float:right">¥${deliveryFee}</span>`;
    itemList.appendChild(delivery);

    total += deliveryFee;
    document.getElementById('total').innerText = `${total}`;
});

// 切换支付方式
document.addEventListener('click', e => {
    //判断当前点击的DOM元素是否是payItem或其子元素
    const payItem = e.target.closest('.pay-item');
    //如果是
    if (payItem) {
        //移除所有selected类
        document.querySelectorAll('.pay-item').forEach(el => el.classList.remove('selected'));
        //为当前点击的元素设置selected类
        payItem.classList.add('selected');
    }
});

window.onload = function(){
    //获取显示隐藏按钮DOM对象
    let showBtn = document.getElementById('showBtn');
    //获取订单明细DOM对象
    let itemList = document.getElementById('itemList');
    //设置默认订单明细隐藏
    itemList.style.display='none';

    showBtn.onclick = function(){
        //判断订单明细DOM对象是否隐藏，如果是，就显示，否则就隐藏
        if(itemList.style.display=='none'){
            itemList.style.display='block';
        }else{
            itemList.style.display='none';
        }
    }
}

function returnIndex(){
    window.location.href = 'index.html';
}

function toOrder(){
    window.location.href = 'myOrder.html';
}
